﻿using UnityEngine;

namespace MFramework
{
    // MonoBehaviour封装，自己管理Tick生命周期逻辑，提高效率
    public abstract class MonoBehaviourExtend : MonoBehaviour
    {
        //轮询优先级，order越小越靠前轮询
        protected ExcuteOrderDefine excuteOrder = ExcuteOrderDefine.DEFAULT;

        private uint updateID;
        private uint fixedUpdateID;
        private uint lateUpdateID;

        protected virtual void OnEnabled() { }
        protected virtual void OnDisabled() { }
        protected virtual void OnUpdate() { }
        protected virtual void OnLateUpdate() { }
        protected virtual void OnFixedUpdate() { }

        private void UpdateEx()
        {
            OnUpdate();
        }

        private void LateUpdateEx()
        {
            OnLateUpdate();
        }

        private void FixedUpdateEx()
        {
            OnFixedUpdate();
        }

        private void OnEnable()
        {
            updateID = MonoRuntime.Inst.Regist(MonoRuntime.MonoLifecycle.Update, UpdateEx, excuteOrder);
            lateUpdateID = MonoRuntime.Inst.Regist(MonoRuntime.MonoLifecycle.LateUpdate, LateUpdateEx, excuteOrder);
            fixedUpdateID = MonoRuntime.Inst.Regist(MonoRuntime.MonoLifecycle.FixedUpdate, FixedUpdateEx, excuteOrder);

            OnEnabled();
        }

        private void OnDisable()
        {
            MonoRuntime.Inst.UnRegist(MonoRuntime.MonoLifecycle.Update, updateID);
            MonoRuntime.Inst.UnRegist(MonoRuntime.MonoLifecycle.LateUpdate, lateUpdateID);
            MonoRuntime.Inst.UnRegist(MonoRuntime.MonoLifecycle.FixedUpdate, fixedUpdateID);

            OnDisabled();
        }
    }
}
